<template>
  <div class="page">
    <div class="custom-calendar">
      <!-- 日历头部 -->
      <div class="calendar-header">
        <!-- 当前日期显示 -->
        <span class="header-date">{{ displayDate }}</span>
        <!-- 回到今天按钮 -->
        <span class="header-today" v-if="goTodayHe" @click.stop="goToday">回到今天</span>
      </div>

      <!-- 日历内容区域，包括触摸事件监听 -->
      <div class="calendar-content" @touchmove="handleTouchMove" @touchstart="handleTouchStart"
        @touchend="handleTouchEnd">
        <!-- 星期标题 -->
        <div class="week-row">
          <div class="week-cell" v-for="day in fullWeekDays" :key="day">{{ day }}</div>
        </div>

        <!-- 日期网格 -->
        <div class="date-grid" :class="{ collapsed: !isExpanded }">
          <div class="date-cell" v-for="(date, index) in displayedDates" :key="date.date.toISOString()" :class="{
            'other-month': !date.isCurrentMonth, // 是否是当前月
            'today': date.isToday,              // 是否是今天
            'selected': date.isSelected         // 是否被选中
          }" @click="selectDate(date)">
            <div class="date-inner">{{ date.day }}</div>
            <!-- 考勤状态显示 -->
            <div class="status-container" v-if="date.isCurrentMonth && hasAttendanceData(date.date)">
              <div class="status-dot" :class="getStatusClass(date.date, 'am')"></div>
              <div class="status-dot" :class="getStatusClass(date.date, 'pm')"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 展开/收起按钮 -->
      <div class="calendar-toggle-line" @click="toggleExpand">
        <div class="line"></div>
        <div class="arrow-icon">
            <u-icon v-if="!isExpanded" color="#999" name="arrow-down" size="24"></u-icon>
            <u-icon v-else color="#999" name="arrow-up" size="24"></u-icon>
        </div>
        <div class="line"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';
import { companyclockmonthrecord, companyleavemonth, getpersonsbyDept } from '../../../apis/Mytodolist/Waitformetohandleit.js';

export default {
  data () {
    return {
      currentDate: new Date(), // 当前选中的日期
      isExpanded: false, // 是否展开日历（false 表示显示一周）
      fullWeekDays: ['一', '二', '三', '四', '五', '六', '日'], // 星期标题
      touchStartX: 0, // 触摸起点 X 坐标
      touchEndX: 0, // 触摸终点 X 坐标
      refreshKey: 0, // 强制刷新日期的key
      user: {
        worker_name: '',
        depart_id:''
      },
      // 人员数据
      person_list: {},
      kaoqin_lists:[],
    };
  },
  computed: {
      ...mapStores(useUserStore),
    // 展示的日期字符串，如 "2025 05.13"
    displayDate () {
      const year = this.currentDate.getFullYear();
      const month = (this.currentDate.getMonth() + 1).toString().padStart(2, '0');
      const day = this.currentDate.getDate().toString().padStart(2, '0');
      return `${year} | ${month}.${day}`;
    },

    // 获取当前月需要展示的所有日期（含补充的前后月份）
    visibleDates () {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      const today = new Date();

      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const firstDayOfWeek = firstDay.getDay() || 7; // 处理周日为 0 的情况

      const dates = [];

      // 添加上个月的部分日期填充空格
      const prevMonthDays = firstDayOfWeek - 1;
      const prevMonthLastDay = new Date(year, month, 0).getDate();
      for (let i = prevMonthDays; i > 0; i--) {
        const day = prevMonthLastDay - i + 1;
        dates.push({
          day,
          date: new Date(year, month - 1, day),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false,
        });
      }

      // 当前月日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i);
        const isToday = date.toDateString() === today.toDateString();
        const isSelected = date.toDateString() === this.currentDate.toDateString();
        dates.push({
          day: i,
          date,
          isCurrentMonth: true,
          isToday,
          isSelected,
        });
      }

      // 添加下个月的日期填补 6 行 × 7 列 = 42 个格子
      const remainingCells = 42 - dates.length;
      for (let i = 1; i <= remainingCells; i++) {
        dates.push({
          day: i,
          date: new Date(year, month + 1, i),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false,
        });
      }

      return dates;
    },

    // 根据是否展开来决定展示全部日期还是一周
    displayedDates () {
      this.refreshKey; // 触发计算更新
      if (this.isExpanded) {
        return this.visibleDates;
      } else {
        // 找到当前选中日期所在周，并截取那一行
        const selectedIndex = this.visibleDates.findIndex(
          (d) => d.date.toDateString() === this.currentDate.toDateString()
        );
        if (selectedIndex === -1) return [];
        const startOfWeek = Math.floor(selectedIndex / 7) * 7;
        return this.visibleDates.slice(startOfWeek, startOfWeek + 7);
      }
    },

    // 判断回到今天是否显示
    goTodayHe () {
      const today = new Date();
      const current = this.currentDate;

      return (
        today.getFullYear() !== current.getFullYear() ||
        today.getMonth() !== current.getMonth() ||
        today.getDate() !== current.getDate()
      );
    },
  },
  created() {
    this.user = this.userStore.user ? this.userStore.user : {
      worker_name: '',
      depart_id:1
    };
    // this.Getcompanyclockmonthrecord()
  },
  methods: {
    // 检查是否有考勤数据
    hasAttendanceData(date) {
      if (!this.kaoqin_lists.length) return false;
      
      const dateStr = this.formatDate(date);
      return this.kaoqin_lists[0].date_info.some(item => item.date === dateStr);
    },
    
    // 获取状态类
    getStatusClass(date, period) {
      if (!this.kaoqin_lists.length) return '';
      
      const dateStr = this.formatDate(date);
      const record = this.kaoqin_lists[0].date_info.find(item => item.date === dateStr);
      
      if (!record) return '';
      
      const status = period === 'am' ? record.am_status : record.pm_status;
      
      // 状态映射
      switch(status) {
        case '/': // 正常
          return 'normal';
        case 'G': // 公休
          return 'rest';
        case 'T': // 调休
        case '○': // 事假
        case 'N': // 年假
        case '产': // 产假
        case '△': // 病假
          return 'leave';
        case 'X': // 缺勤
          return 'absent';
        case '补': // 补卡
          return 'makeup';
        // 其他状态可以根据需要添加
        default:
          return '';
      }
    },
    
    // 日期格式化
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    async Getcompanyclockmonthrecord(){
     try {
          // 入职查询
          const workInfo =  await getpersonsbyDept({
            token: this.userStore.user.token,
            worker_id:this.user.worker_id,
            year_month:"2025-05",
            bm_id:this.user.depart_id
          }).catch((err)=>{
            console.log('入职err',err);
          })

          workInfo.data.forEach(item => {
              this.person_list[item.phone] = item;
          })

          // 查询考勤报表
          let res =  await companyclockmonthrecord({
              token: this.userStore.user.token,
              year_month:"2025-05",
              depart_id:this.user.depart_id,
              end_day:"2025-05-31",
              start_day:"2025-05-01"
          })

          // 考勤审批数据
          const apply  = await companyleavemonth({
              token: this.userStore.user.token,
              year_month:"2025-05",
              depart_id:this.user.depart_id,
              end_day:"2025-05-31",
              start_day:"2025-05-01"
          })

          const applyData = apply.data
          // 筛选个人信息
          let clockData =  res.data.find((item)=>{
            return item.phone = this.user.phone && item.worker_name == this.user.worker_name
          })

          // 处理打卡数据
          this.kaoqin_lists = [clockData].map((item) => { 
            item.chuqin = 0;
            item.nianjia = 0;
            item.queqin = 0;
            item.tiaoxiu = 0;
            item.chanjia = 0;
            item.bingjia = 0;
            item.shijia = 0;
            item.syxj_sy = 0;
            item.syxj_lj = 0;
            item.ndxj_lj = 0;

            // 过滤当前人审批数据
            const itemApply = {};
            applyData.forEach(a => {
              if(item.phone === a.phone) {
                itemApply[a.biz_date] = a;
              }
            })

            item.date_info.forEach((child) => {
              // ftype 补卡 事假 病假 年假 调休 产假
              // opr_type 上午 下午 全天
              // (／)出勤 (T)调休 (○)事假 (╳)旷工 早退/迟到(分钟) (G)公休 (□)出差 (Ｎ)年假 (H)婚假 (S)丧假 (陪)陪产假 (产)产假 (△)病假 (补)补卡 (-)未入职 (离)离职

              // 入职前处理
              if(this.person_list[item.phone] && this.person_list[item.phone].entry_date) {
                const entry_date = this.person_list[item.phone].entry_date;
                if(entry_date > child.date) {
                  child.am_status = '-';
                  child.pm_status = '-';
                  return;
                }
              }

              // 公休节假
              if (child.am_status === 'G') {
                child.workTime = 0;
                return
              }

              // 调休
              if (itemApply[child.date] && itemApply[child.date].ftype === '调休') {
                const result = this.setSymbol(child, 'T', itemApply);
                item.tiaoxiu += result;
                if(result === 1) return;
              }

              // 事假
              if (itemApply[child.date] && itemApply[child.date].ftype === '事假') {
                const result = this.setSymbol( child, '○', itemApply);
                item.shijia += result;
                if(result === 1) return;
              }

              // 年假
              if (itemApply[child.date] && itemApply[child.date].ftype === '年假') {
                const result = this.setSymbol( child, 'N', itemApply);
                item.nianjia += result;
                if(result === 1) return;
              }

              // 产假
              if (itemApply[child.date] && itemApply[child.date].ftype === '产假') {
                const result = this.setSymbol( child, '产', itemApply);
                item.chanjia += result;
                if(result === 1) return;
              }

              // 病假
              if (itemApply[child.date] && itemApply[child.date].ftype === '病假') {
                const result = this.setSymbol( child, '△', itemApply);
                item.bingjia += result;
                if(result === 1) return;
              }

              // 补卡
              if (itemApply[child.date] && itemApply[child.date].ftype === '补卡') {
                if (itemApply[child.date].opr_type === '全天') {
                  child.am_status = '补';
                  child.pm_status = '补';
                }
                if (itemApply[child.date].opr_type === '上午') {
                  child.am_status = '补';
                }
                if (itemApply[child.date].opr_type === '下午') {
                  child.pm_status = '补';
                }
              }


              // 上下班正常
              if ((child.am_status === '/' || child.am_status === '补') && (child.pm_status === '/' || child.pm_status === '补')) {
                const sb = new Date(`${child.date} ${child.am_clock_time}`).getTime();
                const xb = new Date(`${child.date} ${child.pm_clock_time}`).getTime();
                const diff = xb - sb;
                child.workTime = (diff / 1000 / 60 / 60).toFixed(1);

                if (child.week === '周六') {
                  item.chuqin += 0.5;
                } else {
                  item.chuqin++;
                }
                // 全天正常跳出
                return
              }

              // 上午打卡
              if (child.am_status === '/' || child.am_status === '补') {
                item.chuqin += 0.5;
                child.workTime = 4;
                return;
              }

              // 下午打卡
              if (child.pm_status === '/' || child.pm_status === '补') {
                item.chuqin += 0.5;
                child.workTime = 4;
                return;
              }

              // 均未打卡
              if (child.am_status === 'X' && child.pm_status === 'X') {
                item.queqin++;
                child.workTime = 0;
              }

            })
            return item
          });
        
     } catch (error) {
        console.error('获取考勤数据失败:', error);
     }
    },
    // 切换展开/收起状态
    toggleExpand () {
      this.isExpanded = !this.isExpanded;
    },

    // 回到今天
    goToday () {
      this.currentDate = new Date();
    },

    // 选择某个日期
    selectDate (date) {
      this.currentDate = new Date(date.date);
    },

    // 上个月
    prevMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1);
    },

    // 下个月
    nextMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);
    },

    // 触摸开始事件
    handleTouchStart (e) {
      this.touchStartX = e.changedTouches[0].clientX;
    },

    // 触摸结束，触发滑动判断
    handleTouchEnd (e) {
      this.touchEndX = e.changedTouches[0].clientX;
      this.handleSwipe();
    },
    // 阻止默认行为（如滚动）
    handleTouchMove (e) {
      e.preventDefault()
    },

    // 判断滑动方向并翻月
    handleSwipe () {
      if (!this.isExpanded) return;
      const diffX = this.touchStartX - this.touchEndX;
      const swipeThreshold = 50; // 最小滑动距离阈值

      if (diffX > swipeThreshold) {
        this.nextMonth();
      } else if (diffX < -swipeThreshold) {
        this.prevMonth();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  user-select: none;
}

.custom-calendar {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    position: relative;

    .header-date {
      font-size: 16px;
      font-weight: bold;
      flex-grow: 1;
      text-align: left;
    }

    .header-today {
      position: absolute;
      left: 80%;
      transform: translateX(-50%);
      font-size: 14px;
      color: #ccc;
      cursor: pointer;
      text-align: right;
    }
  }

  .calendar-content {
    padding: 8px 0;
    touch-action: pan-x pan-y;

    .week-row {
      display: flex;
      padding: 8px 0;

      .week-cell {
        flex: 1;
        text-align: center;
        font-size: 12px;
        color: #666;
      }
    }

    .date-grid {
      display: flex;
      flex-wrap: wrap;

      &.collapsed {
        flex-wrap: nowrap;
      }

      .date-cell {
        flex: 0 0 14.28%;
        height: 50px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        cursor: pointer;
        position: relative;

        .date-inner {
          width: 28px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          z-index: 1;
        }

        &.other-month {
          color: #ccc;
        }

        &.today .date-inner {
          color: #007aff;
          font-weight: bold;
        }

        &.selected .date-inner {
          background-color: #1890ff;
          color: white;
          border-radius: 50%;
        }
      }
    }
  }

  .calendar-toggle-line {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px 0;
    cursor: pointer;

    .line {
      flex: 1;
      height: 1px;
      background-color: #ccc;
      margin: 0 8px;
    }

    .arrow-icon {
      font-size: 14px;
      color: #666;
      padding: 0 4px;
    }
  }
}

// 考勤状态样式
.status-container {
  display: flex;
  justify-content: center;
  gap: 2px;
  margin-top: 2px;
  width: 100%;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  
  // 正常状态
  &.normal {
    background-color: #52c41a;
  }
  
  // 公休状态
  &.rest {
    background-color: #bfbfbf;
  }
  
  // 请假状态
  &.leave {
    background-color: #1890ff;
  }
  
  // 缺勤状态
  &.absent {
    background-color: #f5222d;
  }
  
  // 迟到/早退
  &.late {
    background-color: #faad14;
  }
  
  // 补卡
  &.makeup {
    background-color: #722ed1;
  }
}

// 考勤图例样式
.attendance-legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px;
  padding: 16px;
  margin-top: 16px;
  background: #f9f9f9;
  border-radius: 8px;
  
  .legend-item {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #666;
    
    .legend-dot {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 4px;
      
      // 应用相同的颜色类
      &.normal { background-color: #52c41a; }
      &.rest { background-color: #bfbfbf; }
      &.leave { background-color: #1890ff; }
      &.absent { background-color: #f5222d; }
      &.late { background-color: #faad14; }
      &.makeup { background-color: #722ed1; }
    }
  }
}
</style>